package com.swf.seed.spring.mail;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

public class SpringMail {
	private JavaMailSenderImpl mailSender;
	private SimpleMailMessage simpleMailMessage;

	public void setMailSender(JavaMailSenderImpl mailSender) {
		this.mailSender = mailSender;
	}

	public void setSimpleMailMessage(SimpleMailMessage simpleMailMessage) {
		this.simpleMailMessage = simpleMailMessage;
	}

	public void sendSimpleMessage(String subject, String content) {
		// 设定邮件参数
		simpleMailMessage.setFrom(mailSender.getUsername());
		simpleMailMessage.setSubject(subject);
		simpleMailMessage.setText(content);
		// 发送邮件
		mailSender.send(simpleMailMessage);
	}

	public void sendHTMLMessage()
			throws MessagingException {
		// 设定邮件参数
		// 建立邮件消息,发送简单邮件和html邮件的区别
		MimeMessage mailMessage = mailSender.createMimeMessage();
		MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage);

		// 设置收件人，寄件人
		messageHelper.setTo("shenwf10476@hundsun.com");
		messageHelper.setFrom(mailSender.getUsername());
		messageHelper.setSubject("测试HTML邮件！");
		// true 表示启动HTML格式的邮件
		messageHelper
				.setText(
						"<html><head></head><body><h1>hello!!spring html Mail</h1></body></html>",
						true);

		// 发送邮件
		mailSender.send(mailMessage);
	}

	public void sendAttachImageMessage() throws MessagingException {
		// 设定邮件参数
		// 建立邮件消息,发送简单邮件和html邮件的区别
		MimeMessage mailMessage = mailSender.createMimeMessage();
		MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,
				true);

		// 设置收件人，寄件人
		messageHelper.setTo("shenwf10476@hundsun.com");
		messageHelper.setFrom(mailSender.getUsername());
		messageHelper.setSubject("测试邮件中嵌套图片!！");
		// true 表示启动HTML格式的邮件
		messageHelper.setText(
				"<html><head></head><body><h1>hello!!spring image html mail</h1>"
						+ "<img src=\"cid:aaa\"/></body></html>", true);

		ClassPathResource img = new ClassPathResource("pic.jpg");
		messageHelper.addInline("aaa", img);

		// 发送邮件
		mailSender.send(mailMessage);
	}

	public void sendAttachFileMessage() throws MessagingException {
		MimeMessage mailMessage = mailSender.createMimeMessage();
		MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage,
				true, "utf-8");

		// 设置收件人，寄件人
		messageHelper.setTo("shenwf10476@hundsun.com");
		messageHelper.setFrom(mailSender.getUsername());
		messageHelper.setSubject("测试邮件中上传附件!！");
		// true 表示启动HTML格式的邮件
		messageHelper.setText(
				"<html><head></head><body><h1>你好：附件中有学习资料！</h1></body></html>",
				true);

		ClassPathResource log4j = new ClassPathResource("log4j.xml");
		messageHelper.addAttachment("log4j.xml", log4j);

		// 发送邮件
		mailSender.send(mailMessage);
	}

}
